package com.snack.shop.task;

import com.snack.shop.service.OrderService;
import com.snack.shop.service.PickupOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 订单超时处理定时任务
 *
 * <p>负责处理以下场景：
 * <ul>
 *     <li>待支付超过15分钟的订单自动取消</li>
 *     <li>代取订单送达超过24小时未确认收货自动进入待结算</li>
 * </ul>
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class OrderTimeoutTask {

    private final OrderService orderService;
    private final PickupOrderService pickupOrderService;

    /**
     * 每分钟检查一次待支付超时订单
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void autoCancelUnpaidOrders() {
        try {
            LocalDateTime deadline = LocalDateTime.now().minusMinutes(15);
            int count = orderService.autoCancelUnpaidOrders(deadline);
            if (count > 0) {
                log.info("自动取消超时未支付订单 {} 条", count);
            }
        } catch (Exception e) {
            log.error("自动取消超时未支付订单失败", e);
        }
    }

    /**
     * 每小时检查一次已送达但超时未确认的代取订单
     */
    @Scheduled(cron = "0 5 * * * ?")
    public void autoConfirmDeliveredErrandOrders() {
        try {
            LocalDateTime deadline = LocalDateTime.now().minusDays(1);
            int count = pickupOrderService.autoConfirmDeliveredOrders(deadline);
            if (count > 0) {
                log.info("自动确认送达超时的代取订单 {} 条", count);
            }
        } catch (Exception e) {
            log.error("自动确认代取订单送达超时失败", e);
        }
    }
}

